package generatorService

import (
	generatorModel "CommonsProject/models/generatorModel"
	"CommonsProject/pkg/tools/generator"
	"CommonsProject/pkg/tools/sqlTool"
	"CommonsProject/repository/generatorRepository"
	"archive/zip"
	"bytes"
	"fmt"
	"github.com/gin-gonic/gin"
)

type TableProduceService struct {
	Repository *generatorRepository.TableProduceRepository
}

// AddSysTable 添加表
func (service *TableProduceService) AddSysTable(table *generatorModel.Table) {
	service.Repository.AddSysTable(table)
}

// RemoveSysTable 删除表
func (service *TableProduceService) RemoveSysTable(id int) {
	service.Repository.RemoveSysTable(id)
}

// ModifySysTable 修改表
func (service *TableProduceService) ModifySysTable(table *generatorModel.Table) {
	service.Repository.ModifySysTable(table)
}

// FindSysTableById 通过ID查询生成表
func (service *TableProduceService) FindSysTableById(id int) generatorModel.Table {
	return service.Repository.FindSysTableById(uint(id))
}

// FindSysTable 查询所有的生成表
func (service *TableProduceService) FindSysTable(table *generatorModel.Table, pageNum, PageSize int) sqlTool.PageInfo {
	return service.Repository.FindSysTable(table, pageNum, PageSize)
}

// ShowProduce 预览生成
func (service *TableProduceService) ShowProduce(id int) gin.H {
	table := service.Repository.FindSysTableById(uint(id))
	return gin.H{
		"models":     generator.Models(table),
		"controller": generator.Controller(table),
		"service":    generator.Service(table),
		"repository": generator.Repository(table),
		"routers":    generator.Routers(table),
		"sql":        generator.SQL(table),
	}
}

// Download 下载生成代码
func (service *TableProduceService) Download(id int) bytes.Buffer {
	table := service.Repository.FindSysTableById(uint(id))
	var buf bytes.Buffer
	zipFile := zip.NewWriter(&buf)

	if len(table.FullPackage) != 0 {
		table.FullPackage = "/" + table.FullPackage
	}

	models, _ := zipFile.Create(fmt.Sprintf("/models%s/%s.go", table.FullPackage, table.StructName))
	models.Write([]byte(generator.Models(table)))

	controller, _ := zipFile.Create(fmt.Sprintf("/controller%s/%s.go", table.FullPackage, table.StructName))
	controller.Write([]byte(generator.Controller(table)))

	serviceFile, _ := zipFile.Create(fmt.Sprintf("/service%s/%s.go", table.FullPackage, table.StructName))
	serviceFile.Write([]byte(generator.Service(table)))

	repository, _ := zipFile.Create(fmt.Sprintf("/repository%s/%s.go", table.FullPackage, table.StructName))
	repository.Write([]byte(generator.Repository(table)))

	routers, _ := zipFile.Create(fmt.Sprintf("/routers%s/%s.go", table.FullPackage, table.StructName))
	routers.Write([]byte(generator.Routers(table)))

	sql, _ := zipFile.Create("sql.sql")
	sql.Write([]byte(generator.SQL(table)))

	// 关闭 ZIP writer，确保所有数据都被写入缓冲区
	if err := zipFile.Close(); err != nil {
		panic("创建ZIP文件失败")
	}

	return buf
}
